<template>
  <div class="app-container cart-style">
    <!-- 搜索区域：新增产品名称搜索，优化布局 -->
    <div class="search-bar">
      <el-form :model="queryParams" ref="queryForm" size="small" inline label-width="70px">
        <el-form-item label="产品名称" prop="productName">
          <el-input
            v-model="queryParams.productName"
            placeholder="请输入产品名称搜索"
            clearable
            @keyup.enter.native="handleQuery"
            class="search-input"
          />
        </el-form-item>
        <el-form-item label="产品类型" prop="productType">
          <el-select
            v-model="queryParams.productType"
            placeholder="产品类型"
            clearable
            @change="handleQuery"
            class="search-select"
          >
            <el-option label="门票" value="门票"></el-option>
            <el-option label="住宿" value="住宿"></el-option>
            <el-option label="餐饮" value="餐饮"></el-option>
            <el-option label="文创" value="文创"></el-option>
            <el-option label="农产品" value="农产品"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="订单状态" prop="status">
          <el-select
            v-model="queryParams.status"
            placeholder="订单状态"
            clearable
            @change="handleQuery"
            class="search-select"
          >
            <el-option label="待支付" value="待支付"></el-option>
            <el-option label="已支付" value="已支付"></el-option>
            <el-option label="已取消" value="已取消"></el-option>
            <el-option label="已完成" value="已完成"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery" class="reset-btn">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 操作按钮区 -->
    <div class="operation-bar">
      <el-button
        type="danger"
        plain
        icon="el-icon-delete"
        size="mini"
        :disabled="multiple"
        @click="handleDelete"

      >
        <i class="el-icon-delete"></i> 批量删除
      </el-button>
      <el-button
        type="warning"
        plain
        icon="el-icon-download"
        size="mini"
        @click="handleExport"

      >
        <i class="el-icon-download"></i> 导出订单
      </el-button>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList" class="right-toolbar"></right-toolbar>
    </div>

    <!-- 订单列表：购物车风格表格 -->
    <div class="cart-table-container">
      <el-table
        v-loading="loading"
        :data="orderList"
        @selection-change="handleSelectionChange"
        border
        highlight-current-row
        class="cart-table"
      >
        <el-table-column type="selection" width="50" align="center" />
        <el-table-column label="商品信息" align="center" min-width="300">
          <template slot-scope="scope">
            <div class="product-info">
              <!-- 商品缩略图 -->
              <el-image
                :src="scope.row.productImage"
                class="product-img"
                :preview-src-list="[scope.row.productImage]"
                fit="cover"
              ></el-image>
              <!-- 商品详情 -->
              <div class="product-detail">
                <div class="product-name">{{ scope.row.productName || '未知商品'}}</div>
                <div class="product-type">类型：{{ scope.row.productType || '未知类型'}}</div>
                <div class="product-shop">商店：{{ depts[scope.row.deptId] || '未知商店' }}</div>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="单价" align="center" prop="unitPrice" min-width="80">
          <template slot-scope="scope">
            <span class="price">¥{{ scope.row.unitPrice }}</span>
          </template>
        </el-table-column>
        <el-table-column label="数量" align="center" prop="quantity" min-width="80" />
        <el-table-column label="小计" align="center" min-width="100">
          <template slot-scope="scope">
            <span class="subtotal">¥{{ (scope.row.unitPrice * scope.row.quantity).toFixed(2) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="订单状态" align="center" min-width="100">
          <template slot-scope="scope">
            <el-tag
              :type="scope.row.status === '已支付' ? 'success' :
                     scope.row.status === '待支付' ? 'warning' :
                     scope.row.status === '已取消' ? 'danger' : 'info'"
              class="status-tag"
            >
              {{ scope.row.status }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="下单时间" align="center" prop="createTime" min-width="160">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d} {h}:{i}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" min-width="120">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="handleDelete(scope.row)"
              class="operate-btn delete-btn"
            >删除</el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-credit-card"
              @click="handlePay(scope.row)"
              v-if="scope.row.status === '待支付'"
              class="operate-btn pay-btn"
            >支付</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 分页 -->
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
      class="pagination"
    />
  </div>
</template>

<script>
import { listOrder, delOrder, updateOrder } from "@/api/system/order";
import { listDepts } from "@/api/system/depts";
import { listCultural } from "@/api/system/cultural";
import { listAgricultural } from "@/api/system/agricultural";
import { listFood } from "@/api/system/food";
import { listAccommodation } from "@/api/system/accommodation";
import { listTicket } from "@/api/system/ticket";
import {parseTime} from "@/utils/ruoyi";

export default {
  name: "PersonalOrderCart",
  data() {
    return {
      loading: true,
      showSearch: true,
      ids: [],
      single: true,
      multiple: true,
      total: 0,
      orderList: [],
      depts: {}, // 商店缓存
      products: { // 产品缓存
        文创: {}, 农产品: {}, 餐饮: {}, 住宿: {}, 门票: {}
      },
      // 搜索参数：新增productName
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        userId: this.$store.state.id,
        productName: null, // 产品名称搜索
        productType: null,
        status: null
      },
    };
  },
  created() {
    // 更严格的登录检查
    const token = this.$store.state.token;
    if (!token) {
      this.$message.warning("请先登录查看订单");
      this.$router.push("/login");
      return;
    }

    this.initData();
  },
  methods: {
    parseTime,
    // 初始化部门和产品数据
    async initData() {
      try {
        // 1. 加载部门数据
        const deptRes = await listDepts({ pageNum: 1, pageSize: 1000 });
        this.depts = deptRes.rows.reduce((map, dept) => {
          map[dept.deptId] = dept.deptName;
          return map;
        }, {});

        // 2. 加载产品数据
        await Promise.all([
          this.loadProducts("文创", listCultural),
          this.loadProducts("农产品", listAgricultural),
          this.loadProducts("餐饮", listFood),
          this.loadProducts("住宿", listAccommodation),
          this.loadProducts("门票", listTicket)
        ]);

        // 3. 加载订单
        this.getList();
      } catch (error) {
        console.error("初始化失败:", error);
        this.$message.error("数据加载失败，请重试");
        this.loading = false;
      }
    },

    // 加载产品数据
    async loadProducts(type, apiFn) {
      try {
        const res = await apiFn({ pageNum: 1, pageSize: 1000 });
        // 确保数据存在且是数组
        const rows = Array.isArray(res?.rows) ? res.rows : [];

        // 初始化该类型的产品缓存
        this.products[type] = {};

        rows.forEach(product => {
          if (product && product.id) {
            this.products[type][product.id] = product;
          }
        });
      } catch (error) {
        console.error(`加载${type}产品失败:`, error);
      }
    },

    // 获取订单列表（含产品名称搜索过滤）
    async getList() {
      this.loading = true;

      // 安全获取用户ID
      const userId = this.$store.state.id;
      if (!userId) {
        this.$message.error("用户信息获取失败");
        this.loading = false;
        return;
      }

      this.queryParams.userId = userId;

      try {
        const res = await listOrder(this.queryParams);
        // 确保数据存在且是数组
        const rows = Array.isArray(res?.rows) ? res.rows : [];

        this.orderList = rows.map(order => {
          // 安全访问产品信息
          const productTypeData = this.products[order.productType] || {};
          const product = productTypeData[order.productId] || {};

          return {
            ...order,
            productName: product.name || `未知商品(${order.productId})`,
            productImage: this.getProductImage(product)
          };
        });

        this.total = res.total || 0;
      } catch (error) {
        console.error("获取订单失败:", error);
        this.$message.error("获取订单失败，请重试");
      } finally {
        this.loading = false;
      }
    },

    // 获取产品图片
   getProductImage(product) {
    if (!product) return ""; // 无产品信息时返回空
    const imgUrl = product.imageUrl || product.picUrl || "";
    const firstImg = imgUrl.split(",")[0];
    if (!firstImg) return ""; // 无图片时返回空
    // 拼接图片路径
    return process.env.NODE_ENV === "development"
      ? `${process.env["VUE_APP_BASE_API"]}${firstImg}`
      : `http://localhost:8085/dev-api${firstImg}`;
  },

    // 搜索与重置
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    resetQuery() {
      this.resetForm("queryForm");
      this.queryParams.userId = this.$store.state.user.id;
      this.getList();
    },

    // 选择逻辑
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },

    // 支付操作
handlePay(row) {
  // 拼接正确的接口路径（包含前端代理前缀/dev-api）
  const payUrl = `http://localhost:8080/alipay/pagePay?orderId=${row.id}`;
  window.open(payUrl, '_blank');
},

    // 提交支付
    submitForm() {
      this.$refs.form.validate(valid => {
        if (valid) {
          updateOrder({
            id: this.form.id,
            status: "已支付",
            payTime: this.form.payTime
          }).then(() => {
            this.$message.success("支付成功");
            this.open = false;
            this.getList();
          }).catch(error => {
            this.$message.error("支付失败：" + (error.msg || "网络错误"));
          });
        }
      });
    },

    // 删除订单
    handleDelete(row) {
      const ids = row ? [row.id] : this.ids;
      if (!ids.length) return;
      this.$confirm(`确定删除选中的${ids.length}个订单？`, "确认", {
        type: "warning"
      }).then(() => {
        delOrder(ids).then(() => {
          this.$message.success("删除成功");
          this.getList();
        }).catch(error => {
          this.$message.error("删除失败：" + (error.msg || "网络错误"));
        });
      });
    },

    // 导出订单
    handleExport() {
      this.download('system/order/export', { ...this.queryParams }, `我的订单_${new Date().getTime()}.xlsx`);
    },

    // 取消
    cancel() {
      this.open = false;
      this.resetForm("form");
    }
  }
};
</script>

<style scoped>
/* 整体购物车风格 */
.cart-style {
  padding: 15px;
  background-color: #f9f9f9;
  min-height: calc(100vh - 120px);
}

/* 搜索栏 */
.search-bar {
  background: #fff;
  padding: 15px;
  border-radius: 6px;
  margin-bottom: 15px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.05);
}

.search-input {
  width: 220px !important;
}

.search-select {
  width: 140px !important;
}

.reset-btn {
  margin-left: 10px !important;
}

/* 操作栏 */
.operation-bar {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 15px;
  padding: 0 5px;
}

.right-toolbar {
  margin-left: auto;
}

/* 订单表格 */
.cart-table-container {
  background: #fff;
  border-radius: 6px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.05);
  overflow: hidden;
}

.cart-table {
  border: none !important;
}

.cart-table th {
  background-color: #f5f7fa !important;
  font-weight: 500 !important;
}

/* 商品信息 */
.product-info {
  display: flex;
  align-items: center;
  padding: 5px 0;
}

.product-img {
  width: 60px;
  height: 60px;
  border-radius: 4px;
  margin-right: 15px;
  border: 1px solid #eee;
}

.product-detail {
  flex: 1;
  line-height: 1.6;
}

.product-name {
  font-weight: 500;
  color: #333;
  margin-bottom: 4px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.product-type, .product-shop {
  font-size: 12px;
  color: #666;
}

/* 价格样式 */
.price {
  color: #e53e3e;
}

.subtotal {
  color: #e53e3e;
  font-weight: 500;
}

/* 状态标签 */
.status-tag {
  padding: 3px 8px;
  font-size: 12px;
}

/* 操作按钮 */
.operate-btn {
  padding: 0 5px !important;
  margin: 0 3px !important;
}

.delete-btn {
  color: #f56c6c !important;
}

.pay-btn {
  color: #409eff !important;
}

/* 分页 */
.pagination {
  margin-top: 15px;
  text-align: right;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .search-input {
    width: 180px !important;
  }
  .search-select {
    width: 120px !important;
  }
  .product-info {
    flex-direction: column;
    align-items: flex-start;
  }
  .product-img {
    margin-bottom: 10px;
  }
}
</style>
